import React, { Component } from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { loginAction } from "../../redux/actions/login";
import { connect } from "react-redux";

// const onFinishFailed = (errorInfo) => {
//   console.log("Failed:", errorInfo);
// };
const formRef = React.createRef();
class LoginForm extends Component {
  state = { loading: false };
  onFinish = async (values) => {
    this.setState({
      loading: true,
    });
    const res = await this.http("admin", {
      Phone: values.username,
      Password: values.password,
    });
    if (values.remember) {
      localStorage.setItem("loginForm", JSON.stringify(values));
    } else {
      localStorage.removeItem("loginForm");
    }
    if (!res.data.dtos[0]) {
      message.error("账号或密码错误！");
      this.setState({
        loading: false,
      });
      return;
    }
    sessionStorage.setItem("userInfo", JSON.stringify(res.data.dtos[0]));
    this.props.loginAction(res.data.dtos[0]);
    this.props.history.replace("/");
  };
  componentDidMount() {
    if (formRef.current) {
      formRef.current.setFieldsValue(
        JSON.parse(localStorage.getItem("loginForm"))
      );
    }
  }
  render() {
    return (
      <div>
        <Form
          ref={formRef}
          name="basic"
          // initialValues={this.state.loginForm}
          onFinish={this.onFinish}
          // onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              {
                required: true,
                message: "请输入您的用户名!",
              },
              // {
              //   len: 11,
              //   message: "用户名长度不正确!",
              // },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message: "用户名必须是英文、数字或下划线组成!",
              },
            ]}
          >
            <Input autoComplete="current-password" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入您的密码!",
              },
              {
                max: 12,
                min: 6,
                message: "密码长度应大于6且小于12!",
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item name="remember" valuePropName="checked">
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button
              loading={this.state.loading}
              type="primary"
              htmlType="submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default connect((state) => ({ userInfo: state.user }), { loginAction })(
  LoginForm
);
